package com.qianchang.microfinance.view.manager;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.SelectPhotoDialog;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.UploadFileBean;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.utils.GlideImageLoader;
import com.qianchang.microfinance.view.base.BaseFragment;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述: 在Fragment中选择图片
 * 修 改 人: zhoulai
 * 修改时间: 2017/5/31 18:12
 */


public abstract class ImageChoseFragment extends BaseFragment implements SelectPhotoDialog.OnViewClickListener {

    private SelectPhotoDialog mDialog;
    public int maxImgCount = 8;

    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int flag;
    UpLoadFileCallback listener;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        selImageList = new ArrayList<>();
    }

    @Override
    protected void initView() {
        super.initView();
        mDialog = new SelectPhotoDialog((Activity) mContext);
        mDialog.setOnViewClickListener(this);
    }


    public void setMaxImageCount(int imageCount) {
        this.maxImgCount = imageCount;
        ImagePicker.getInstance().setSelectLimit(imageCount);
    }

    public void setImages(ArrayList<ImageItem> selImageList) {
        this.selImageList = selImageList;
    }


    public void showSelectPhotoDialog() {
        if (null != mDialog && !mDialog.isShowing()) {
            mDialog.show();
        }
    }

    @Override
    public void onSelectPhotoClick() {
        initImagePickerForSelectPhoto(selImageList == null ? maxImgCount : maxImgCount - selImageList.size());
        Intent intent = new Intent(mContext, ImageGridActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SELECT);
    }

    @Override
    public void onTakePhotoClick() {
        initImagePickerForTakePhoto();
        Intent intent = new Intent(mContext, ImageGridActivity.class);
        intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
        startActivityForResult(intent, REQUEST_CODE_SELECT);
    }

    /**
     * 设置选择图片的ImagePicker配置
     *
     * @param selectedImageSize 已选择图片数量
     */
    public void initImagePickerForSelectPhoto(int selectedImageSize) {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setSelectLimit(selectedImageSize);
        imagePicker.setShowCamera(false);//显示拍照按钮
        imagePicker.setMultiMode(true);//单选多选
        imagePicker.setCrop(false);//允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);//是否按矩形区域保存
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);//裁剪框的形状
        imagePicker.setImageLoader(new GlideImageLoader());
    }

    /**
     * 设置拍照的ImagePicker配置
     */
    public void initImagePickerForTakePhoto() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setMultiMode(false);
        imagePicker.setSelectLimit(1);
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setImageLoader(new GlideImageLoader());

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                parseResult(data);
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                selImageList.clear();
                parseResult(data);
            }
        }
    }

    private void parseResult(Intent data) {
        ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
        if (images != null) {
            selImageList.addAll(images);
            onPhotoResult(selImageList, flag);
        }
    }

    public void clearSelectImages() {
        if (null != selImageList) {
            selImageList.clear();
        }
    }

    public int getFlag() {
        return flag;
    }

    public void setFlag(int flag) {
        this.flag = flag;
    }


    public abstract void onPhotoResult(ArrayList<ImageItem> imageItems, int flag);


    /**
     * 只有图片上传才设置监听
     */
    public void setUpLoadCallBackListener(UpLoadFileCallback listener) {
        this.listener = listener;
    }


    public interface UpLoadFileCallback {
        void onUpLoadSuccess(UploadFileBean uploadFileBean, String imagePath, int flag);
    }


    /**
     * 只有单个文件才支持上传
     *
     * @param imagePath 文件路径
     */
    public void uploadFile(final String imagePath) {
        if (null == imagePath) {
            return;
        }
        File file = new File(imagePath);
        Map<String, File> files = new HashMap<>();
        files.put(file.getName(), file);
        Map<String, String> fileParamsMap = new HashMap<>();
        fileParamsMap.put("allowFile", "jpg,png");
        fileParamsMap.put("fileType", "0");
        fileParamsMap.put("isTransform", "false");
        show();
        DMOKHttpUtils.getInstance().uploadFile(mContext, DMConstant.ApiURL.UPLOAD_FILE, fileParamsMap, "uploadFile", files, new RequestCallBack<ArrayList<UploadFileBean>>() {

            @Override
            public void onSuccess(JsonResult<ArrayList<UploadFileBean>> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    ArrayList<UploadFileBean> uploadFileList = response.getObject();
                    if (null != uploadFileList && uploadFileList.size() > 0) {
                        UploadFileBean uploadFileBean = uploadFileList.get(0);
                        if (null != listener) {
                            listener.onUpLoadSuccess(uploadFileBean, imagePath, flag);
                        }
                    } else {
                        ToastUtil.getInstant().show(mContext, getString(R.string.upload_failed));
                    }
                } else {
                    ToastUtil.getInstant().show(mContext, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(mContext, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }
}
